package com.guigu.eduservice.controller;

import com.guigu.common.utils.R;
import com.guigu.eduservice.entity.MyCollection;
import com.guigu.eduservice.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 收藏表（存储用户收藏的设备信息） 前端控制器
 * </p>
 *
 * @author janecraft
 * @since 2025-09-27
 */
@RestController
@RequestMapping("/eduservice/collection")
public class CollectionController {
    @Autowired
    private CollectionService collectionService;

    @GetMapping("/getAll")
    public List<MyCollection> getAll() {
        return collectionService.list();
    }

    @PostMapping("/addCollection")//添加收藏
    public boolean addCollection(@RequestBody MyCollection collection) {
        System.out.println("collection:" + collection);
        collection.setCreateTime(LocalDateTime.now());
        collection.setUpdateTime(LocalDateTime.now());
        return collectionService.save(collection);
    }

    @GetMapping("/getCollectionByUserId/{userId}")//根据用户ID查询收藏
    public List<MyCollection> getCollectionByUserId(@PathVariable String userId) {
        List<MyCollection> list = collectionService.lambdaQuery().eq(MyCollection::getUserId, userId).list();
        System.out.println("list:" + list);
        return list;
    }
    //根据用户ID查询收藏的设备，进阶版
    @GetMapping("/getCollectionByUserId2/{userId}")//zeng
    public R getCollectionByUserId2(@PathVariable Long userId) {
        List<MyCollection> list = collectionService.getAllByUid(userId);
        return R.ok().data("list", list);
    }

    @GetMapping("/byEquipment/{equipmentId}")//根据设备ID查询收藏
    public R byEquipment(@PathVariable Long equipmentId) {
        List<MyCollection> list = collectionService.lambdaQuery()
                .eq(MyCollection::getEquipmentId, equipmentId)
                .orderByDesc(MyCollection::getCollectionTime)
                .list();

        return R.ok().data("list", list);
    }

    @DeleteMapping("/deleteCollection/{userId}/{equipmentId}")//根据用户ID和设备ID删除收藏
    public boolean deleteCollection(@PathVariable String userId, @PathVariable String equipmentId) {
        return collectionService.lambdaUpdate()
                .eq(MyCollection::getUserId, userId)
                .eq(MyCollection::getEquipmentId, equipmentId)
                .remove();
    }
    @DeleteMapping("/deleteCollectionById/{CId}")
    public R deleteCollectionById(@PathVariable(value = "CId") Long CId) {
        boolean b = collectionService.removeById(CId);
        return b ? R.ok() : R.error();
    }
}
